<template>
	<view>
		<login-redirect v-if="!isLogin" @update:isLogin="handleLoginUpdate" />
			<view v-if="isLogin" class="container">
    <!-- 顶部时间筛选 -->
    <view class="time-filter">
      <text :class="{active: activeTime === 'day'}" @click="switchTime('day')">今日</text>
      <text :class="{active: activeTime === 'week'}" @click="switchTime('week')">本周</text>
      <text :class="{active: activeTime === 'month'}" @click="switchTime('month')">本月</text>
    </view>
    
    <!-- 收入概览 -->
    <view class="income-overview card-style" style="padding: 12px; border-radius: 8px; box-shadow: 0 2px 8px 0 rgba(0,0,0,0.1); margin-bottom: 16px;">
      <view class="income-card">
        <text class="amount" style="font-size: 0.975rem; font-weight: 600; color: white;">总收入</text>
        <text class="amount" style=" padding-left: 20px;">¥{{totalIncome}}</text>
        <text class="subtitle" style="padding-left: 30px;font-weight: 600; color: white;">较昨日 {{incomeChange}}%</text>
      </view>
    </view>
    
    <!-- 收入趋势图表 -->
    <view class="chart-container card-style" style="padding: 16px; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); margin-bottom: 16px;">
      <text class="chart-title" style="font-size: 0.875rem; font-weight: 600; color: #333;">收入趋势</text>
      <canvas id="chartContainer" type="2d" class="chart"></canvas>
    </view>
    
    <!-- 订单统计 -->
    <view class="order-stats card-style" style="min-height: 160px;">
      <text class="chart-title" style="font-size: 0.875rem; font-weight: 600; color: #333;">订单统计</text>
      <view class="order-stats-grid" style="display: grid; grid-template-columns: repeat(2, 1fr); grid-template-rows: repeat(2, 1fr); gap: 12px; padding-top: 16px; height: 120px;">
        <view class="order-stat-item" >
          <text class="stat-label">订单总量</text>
          <text class="stat-value">{{completedOrders}}</text>
        </view>
        <view class="order-stat-item">
          <text class="stat-label">已抢单</text>
          <text class="stat-value">{{completedOrders}}</text>
        </view>
        <view class="order-stat-item">
          <text class="stat-label">配送中</text>
          <text class="stat-value">{{completedOrders}}</text>
        </view>
        <view class="order-stat-item">
          <text class="stat-label">已完成</text>
          <text class="stat-value">{{completedOrders}}</text>
        </view>
      </view>
    </view>
  		</view>
	</view>
</template>

<script>
import * as echarts from 'echarts';
import LoginRedirect from '@/components/login-redirect.vue'

export default {
	onLoad() {
		const token = uni.getStorageSync('token')
		this.isLogin = !!token
		if (!token) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
		}
	},
	components: {
		LoginRedirect
	},
	data() {
		return {
			isLogin: false,
			chartInstance: null,
    
      activeTime: 'day',
      totalIncome: '328.50',
      incomeChange: '+12.5',
      completedOrders: 15,
      avgDeliveryTime: 28,
      breakfastOrders: 3,
      lunchOrders: 7,
      dinnerOrders: 4,
      nightOrders: 1,
      chartData: {
        categories: ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00'],
        series: [{
          name: '收入',
          data: [45, 78, 120, 65, 92, 150, 80],
          color: '#1989fa'
        }]
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if(this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
  },
  methods: {
		handleLoginUpdate(isLogin) {
			this.isLogin = isLogin
		},
    switchTime(time) {
      this.activeTime = time;
      console.log(time);
      // 根据时间筛选更新数据
      const timeData = {
        '今日': {
          categories: ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00'],
          series: [{data: [45, 78, 120, 65, 92, 150, 80]}]
        },
        '本周': {
          categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          series: [{data: [320, 450, 380, 420, 500, 480, 400]}]
        },
        '本月': {
          categories: ['1-5', '6-10', '11-15', '16-20', '21-25', '26-30'],
          series: [{data: [1200, 1500, 1400, 1600, 1800, 2000]}]
        }
      };
      
      // 转换day/week/month为对应的中文键
      const timeMap = {
        'day': '今日',
        'week': '本周',
        'month': '本月'
      };
      const timeKey = timeMap[time] || time;
      
      const selectedData = timeData[timeKey];
      if(!selectedData) return;
      
      this.chartData = {
        ...selectedData,
        series: selectedData.series.map(s => ({...s})) // 创建新对象确保响应式更新
      };
      if(this.chartInstance) {
        this.chartInstance.setOption({
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.chartData.categories,
            axisLine: {
              lineStyle: {
                color: '#999'
              }
            },
            axisLabel: {
              color: '#666'
            }
          },
          yAxis: {
            type: 'value',
            axisLine: {
              show: false
            },
            axisLabel: {
              color: '#999'
            },
            splitLine: {
              lineStyle: {
                color: '#eee',
                width: 1
              }
            }
          },
          series: this.chartData.series.map(item => ({
            ...item,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#1989fa',
              borderColor: '#fff',
              borderWidth: 2,
              shadowColor: 'rgba(0, 0, 0, 0.1)',
              shadowBlur: 5,
              shadowOffsetY: 2
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(25, 137, 250, 0.3)' },
                { offset: 1, color: 'rgba(25, 137, 250, 0.1)' }
              ])
            }
          }))
        }, true); // 第二个参数设置为true表示不合并新旧配置
      }
    },
    initChart() {
      try {
        const canvas = document.getElementById('chartContainer');
        if(!canvas) {
          console.error('Chart container element not found');
          return;
        }
        
        this.chartInstance = echarts.init(canvas, null, {
          width: uni.upx2px(650),
          height: uni.upx2px(400),
          renderer: 'canvas',
          devicePixelRatio: window.devicePixelRatio
        });
      
      // 使用死数据初始化图表
      const chartData = {
        categories: ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00'],
        series: [{
          name: '收入',
          data: [45, 78, 120, 65, 92, 150, 80],
          color: '#1989fa'
        }]
      };
      
      this.chartInstance.setOption({
        backgroundColor: '#ffffff',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: chartData.categories,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        series: [{
          data: chartData.series[0].data,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: chartData.series[0].color,
            borderColor: '#fff',
            borderWidth: 2
          },
          lineStyle: {
            width: 3,
            color: chartData.series[0].color
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: chartData.series[0].color + '60'
              },
              {
                offset: 1,
                color: chartData.series[0].color + '00'
              }
            ])
          }
        }]
      });
      
      }
    catch (err) {
      console.error('ECharts initialization error:', err);
    }
    },
			/*扫一扫核销*/
			scanQrcode: function() {
				console.log(123)
				let self = this;
				//#ifdef H5
				if (this.isWeixin()) {
					// 只允许通过相机扫码
					self.jweixin.scanQRCode({
						needResult: 1,
						scanType: ['qrCode', 'barCode'],
						success: function(res) {
							window.location.href = res.resultStr;
						},
						error: function(res) {
							uni.showToast({
								title: '扫码失败，请重试'
							});
						}
					});
				} else {
					console.log('H5暂只npostedHTTP');
				}
				//#endif
				//#ifndef H5
				// 只允许通过相机扫码

				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						if (res.errMsg == 'scanCode:ok') {
							self.gotoPage(res.path);
						} else {
							uni.showToast({
								title: '扫码失败，请重试'
							});
						}
					}
				});
				//#endif
			},

			/*获取定位方式*/
			getcityData() {
				let self = this;
				// 第一次，如果是公众号，则初始化微信sdk配置
				// #ifdef H5
				if (self.isWeixin()) {
					let sign = uni.getStorageSync('sign');
					if (!sign) {
						uni.showLoading({
							title: '加载中'
						});
						self._postBody(
							'index/index', {
								url: window.location.href
							},
							function(res) {
								uni.setStorageSync('sign', res.data.signPackage);
								sign = res.data.signPackage;
								uni.hideLoading();
								self.getWxLocation(sign);
							}
						);
					} else {
						self.getWxLocation(sign);
					}
				} else {
					self.getLocation();
				}
				// #endif
				// #ifndef H5
				self.getLocation();
				// #endif
			},
			/*授权启用定位权限*/
			onAuthorize() {
				let self = this;
				uni.openSetting({
					success(res) {
						if (res.authSetting['scope.userLocation']) {
							self.isAuthor = true;
							setTimeout(() => {
								// 获取用户坐标
								self.getLocation(res => {});
							}, 1000);
						}
					}
				});
			},
			/*获取用户坐标*/
			getLocation(callback) {
				let self = this;
				uni.getLocation({
					type: 'wgs84',
					success(res) {
						self.longitude = res.longitude;
						self.latitude = res.latitude;
						self.getData();
					},
					fail(err) {
						self.longitude = 0;
						self.latitude = 0;
						uni.showToast({
							title: '获取定位失败，请点击右下角按钮打开定位权限',
							duration: 2000,
							icon: 'none'
						});
						self.getData();
					}
				});
			},
			/* 公众号获取坐标 */
			getWxLocation(signPackage, callback) {
				let self = this;
				var jweixin = require('jweixin-module');
				jweixin.config(JSON.parse(signPackage));
				jweixin.ready(function(res) {
					jweixin.getLocation({
						type: 'wgs84',
						success: function(res) {
							self.longitude = res.longitude;
							self.latitude = res.latitude;
							self.getData();
						},
						fail(err) {
							self.longitude = 0;
							self.latitude = 0;
							self.getData();
						}
					});
				});
				jweixin.error(function(res) {
					console.log(res);
				});
			}
		}
	};
</script>

<style lang="scss">
.container {
  padding: 20rpx 30rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.time-filter {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30rpx;
  padding: 20rpx 0;
  background-color: #fff;
  border-radius: 12rpx;
  
  text {
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    
    &.active {
      background-color: #1989fa;
      color: #fff;
    }
  }
}

.income-overview {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.income-card {
  flex: 1;
  background: linear-gradient(135deg, #1989fa, #46a3ff);
  color: #fff;
  padding: 30rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  
  .title {
    font-size: 28rpx;
    margin-bottom: 10rpx;
  }
  
  .amount {
    font-size: 48rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    font-size: 24rpx;
    opacity: 0.8;
  }
}

.stats-card {
  flex: 1;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  
  .stat-item {
    .label {
      font-size: 24rpx;
      color: #999;
    }
    
    .value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.chart-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .chart-title {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: bold;
  }
  
  .chart {
    width: 100%;
    height: 400rpx;
  }
}

.card-style {
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
      padding: 16px;
      margin: 20px 0;
    }
    
    .order-stats {
  margin: 24px 0 24px;
}

.order-stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.order-stat-item {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  text-align: center;
}

.order-stat-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0,0,0,0.15);
}

.stat-icon {
  width: 40px;
  height: 40px;
  margin: 0 auto 10px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #333;
}

.stat-unit {
  font-size: 12px;
  color: #999;
}

		

		.right {
			width: 290rpx;
			display: flex;
			flex-direction: column;

			.tea-activity,
			.member-gifts {
				width: 100%;
				display: flex;
				padding: 20rpx;
				font-size: $font-size-sm;
				color: $text-color-base;
				align-items: center;
				position: relative;
			}

			.tea-activity {
				background-color: #fdf3f2;
				margin-bottom: 20rpx;
			}

			.member-gifts {
				background-color: #fcf6d4;
			}

			.right-img {
				flex: 1;
				position: relative;
				margin-left: 20rpx;
				margin-right: -20rpx;
				margin-bottom: -20rpx;
				display: flex;
				align-items: flex-end;

				image {
					width: 100%;
				}
			}
		}

		.mark-img {
			width: 30rpx;
			height: 30rpx;
			margin-right: 10rpx;
		}

		.yzclh-img {
			height: 122.96rpx;
			width: 214.86rpx;
		}
	

	.member-news {
		width: 100%;
		margin-bottom: 30rpx;

		.header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0;

			.title {
				font-size: $font-size-lg;
				font-weight: bold;
			}

			.iconfont {
				font-size: 52rpx;
				color: $text-color-assist;
			}
		}

		.list {
			width: 100%;
			display: flex;
			flex-direction: column;

			.item {
				width: 100%;
				height: 240rpx;
				position: relative;

				image {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}

				.title {
					position: relative;
					font-size: 32rpx;
					font-weight: 500;
					width: 100%;
					top: -70rpx;
					left: 16rpx;
					color: #ffffff;
				}
			}
		}
	}

	.collection-box {
		position: fixed;
		width: 380rpx;
		padding: 20rpx;
		top: 20rpx;
		right: 20rpx;
		line-height: 40rpx;
		font-size: 24rpx;
		border-radius: 16rpx;
		background: #ffffff;
		border: 1px solid #eeeeee;
		box-shadow: 0 0 6rpx 0 rgba(0, 0, 0, 0.08);
		z-index: 99;
	}

	.collection-box::after {
		position: absolute;
		content: "";
		display: block;
		right: 140rpx;
		top: -15rpx;
		transform: rotate(45deg);
		width: 30rpx;
		height: 30rpx;
		transform: rotate;
		background: #ffffff;
		border-left: 1px solid #eeeeee;
		border-top: 1px solid #eeeeee;
	}

	.collection-box .point {
		width: 20rpx;
		height: 20rpx;
		font-size: 60rpx;
		line-height: 0;
		color: #666666;
	}

	.collection-box .point-big {
		font-size: 80rpx;
	}

	.collection-box .close-btn {
		position: absolute;
		padding: 0;
		right: 10rpx;
		top: 10rpx;
		width: 40rpx;
		height: 40rpx;
		line-height: 30rpx;
		background: #ffffff;
		color: #999999;
		border-radius: 50%;
	}

	.follow-gzh {
		position: fixed;
		left: 0;
		right: 0;
		bottom: calc(var(--window-bottom));
		border-radius: 16rpx;
		box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
		background: #ffffff;
		z-index: 10;
	}

	.follow-gzh .iconfont {
		display: block;
		position: absolute;
		right: 10rpx;
		top: 10rpx;
		z-index: 99;
	}
</style>